package com.wenlin.page.config;

import javax.sql.DataSource;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.Properties;

@Component
public class MyBatisConfig {
  @Autowired
  DataSource dataSource;
  /***
   *  User:  wenlin
   *  Date:  2017/12/5
   *  Time:  14:18
   *  Description:添加分页拦截器
   **/
  @Bean
  public SqlSessionFactory sqlSessionFactory() {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

    bean.setDataSource(dataSource);
    bean.setTypeAliasesPackage("com.capacity.domain");

    PageHelper pageHelper = new PageHelper();
    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    pageHelper.setProperties(props);
    // 添加插件
    bean.setPlugins(new Interceptor[] { pageHelper });
    // 添加xml目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {

      bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
      return bean.getObject();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

  @Bean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }

  @Bean
  public PlatformTransactionManager annotationDrivenTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
  }
}
